package com.joinval.modules.oss.controller;

import com.joinval.common.exception.JoinvalException;
import com.joinval.common.utils.Result;
import com.joinval.modules.oss.minio.MinioUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import static com.joinval.common.constant.CommonConst.JOINVAL_BUCKET;

@Slf4j
@RestController
@Api(description = "文件上传控制器")
@RequestMapping("minio")
public class MinioController {

    @Autowired
    private MinioUtils minioUtils;

    /**
     * 上传
     *
     * @param file
     * @param request
     * @return
     */
    @ApiOperation(value = "上传")
    @PostMapping("/upload")
    public Result upload(@RequestParam(name = "file", required = false) MultipartFile file, HttpServletRequest request) {
        String url = minioUtils.uploadFileWithDayDir(file, "joinval");
        return Result.ok().data(url);
    }

    @ApiOperation(value = "文件图片上传(检查操作、整改操作相关图片上传)")
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam(name = "file") MultipartFile file) {
        String url = upload(file);
        return Result.ok().data(url);
    }
    private String upload(MultipartFile file) {
        String url = null;
        try {
            minioUtils.createBucketExt(JOINVAL_BUCKET);
            url = minioUtils.uploadFileExt(file, JOINVAL_BUCKET);
        } catch (Exception e) {
            log.error("minioUploadExp", e);
            throw new JoinvalException("minio文件上传出错,请联系管理员");
        }
        return url;
    }

    @ApiOperation(value = "文件图片下载")
    @GetMapping("/downloadFile")
    public Result downloadFile(@RequestParam String urls) throws MalformedURLException, UnsupportedEncodingException {
        String[] urlArray = urls.split(",");
        List<String> filePaths = new ArrayList<>();

        for (String url : urlArray) {
            url = url.trim();
            if (!url.isEmpty()) {
                List<byte[]> images = minioUtils.downloadImagesToBytes(url);
                if (images != null && !images.isEmpty()) {

                    byte[] imageData = images.get(0);

                    // 指定保存文件的路径
                    String fileName = URLDecoder.decode(new URL(url).getPath().substring(url.lastIndexOf('/') + 1), "UTF-8");
                    String filePath = "E:\\fileTest\\" + fileName;

                    // 使用FileOutputStream将字节数据写入文件
                    try (FileOutputStream fos = new FileOutputStream(filePath)) {
                        fos.write(imageData);
                        fos.flush();
                        filePaths.add(filePath);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return Result.error("文件保存失败：" + e.getMessage());
                    }
                } else {
                    // 如果没有下载到数据，记录日志或采取其他措施
                    System.out.println("未从URL " + url + " 下载到图片数据");
                }
            }
        }

        // 如果所有文件都成功保存，则返回成功结果和可能的文件路径列表
        return Result.ok(filePaths.toString());
    }

}
